package com.aiapphub.SystemCode.controller;

import com.aiapphub.BaseCode.common.ResponseResult;
import com.aiapphub.SystemCode.entity.DifyConfig;
import com.aiapphub.SystemCode.service.DifyConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Dify配置控制器
 */
@RestController
@RequestMapping("/api/dify/config")
public class DifyConfigController {

    @Autowired
    private DifyConfigService difyConfigService;

    /**
     * 获取所有配置列表（管理端使用）
     */
    @GetMapping("/list")
    public ResponseResult list() {
        List<DifyConfig> configs = difyConfigService.listAllConfigs();
        Map<String, Object> data = new HashMap<>();
        data.put("data", configs);
        return ResponseResult.okResult(data);
    }

    /**
     * 获取所有启用的配置列表（前端使用）
     */
    @GetMapping("/user/list")
    public ResponseResult userList() {
        List<DifyConfig> configs = difyConfigService.listEnabledConfigs();
        Map<String, Object> data = new HashMap<>();
        data.put("data", configs);
        return ResponseResult.okResult(data);
    }

    /**
     * 根据ID获取配置详情
     */
    @GetMapping("/info/{id}")
    public ResponseResult info(@PathVariable("id") Long id) {
        DifyConfig config = difyConfigService.getConfigById(id);
        Map<String, Object> data = new HashMap<>();
        data.put("data", config);
        return ResponseResult.okResult(data);
    }

    /**
     * 保存配置
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody DifyConfig config) {
        boolean result = difyConfigService.saveConfig(config);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "保存失败");
    }

    /**
     * 更新配置
     */
    @PostMapping("/update")
    public ResponseResult update(@RequestBody DifyConfig config) {
        boolean result = difyConfigService.updateConfig(config);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "更新失败");
    }

    /**
     * 删除配置
     */
    @PostMapping("/delete/{id}")
    public ResponseResult delete(@PathVariable("id") Long id) {
        boolean result = difyConfigService.deleteConfig(id);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "删除失败");
    }

    /**
     * 启用/禁用配置
     */
    @PostMapping("/status")
    public ResponseResult updateStatus(@RequestParam("id") Long id, @RequestParam("status") Integer status) {
        boolean result = difyConfigService.updateStatus(id, status);
        return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "更新状态失败");
    }
}